/**
 * Created by Ysssssss on 2021/5/25.
 */

import React, {forwardRef, useCallback, useContext, useState} from "react";
import CustomizeModal, {CustomizeModalButton, CustomizeModalContext} from "@common/presentational/CustomizeModal";
import {useDispatch} from "react-redux";
import notify from "@utils/tip";
import {bulkAddProductToShelfGroup} from "@sagas/shoppingMall/shoppingMallProduct";
import { Row, Col, Select } from "antd";


const ShelfGroupSelectContent = props => {
    const { callback, shelfGroupList } = props
    const { hide, params } = useContext(CustomizeModalContext)
    const { id, ids } = params
    const dispatch = useDispatch()
    const [groupIds, setGroupId] = useState([])

    const handleGroupIdsChange = id => {
        if (groupIds.includes(id)) {
            setGroupId(groupIds.filter(groupId => groupId !== id))
        } else {
            setGroupId([
                ...groupIds,
                id
            ])
        }
    }

    const submitShelfGroup = () => {
        if (!groupIds.length) {
            notify('请选择分组')
            return;
        }
        dispatch(bulkAddProductToShelfGroup({
            ids: ids || [id],
            groupIds
        }, () => {
            callback && callback()
            hide()
        }))
    }
    return (
        <>
            <Row className="modal-line">
                <div className="multi-select-container">
                    { shelfGroupList.map(group => (
                        <div key={group.id}
                             className={`item-box${groupIds.includes(group.id) ? ' selected' : ''}`}
                             onClick={handleGroupIdsChange.bind(this, group.id)}
                        >{ group.name }</div>
                    )) }
                </div>
            </Row>
            <CustomizeModalButton
                onOk={submitShelfGroup}
                onCancel={hide}
            />
        </>
    )
}


export const ShelfGroupSelectModal = forwardRef((props, ref) => (
    <CustomizeModal title="添加分组" ref={ref}>
        <ShelfGroupSelectContent {...props}/>
    </CustomizeModal>
))